import base64
import json
from json import JSONDecodeError

import faker
import loguru
import requests
from locust import FastHttpUser, task, run_single_user, constant, tag

index_cookie = 2000
fake = faker.Faker()

def get_cookie():
    global index_cookie
    index_cookie += 1
    l = []
    with open('binduser.txt', mode='r', encoding='utf8') as f:
        for account in f:
            l.append(account.strip())
        return str(l[index_cookie])


def enconde_bs64(data):
    data = json.dumps(data)
    encode64 = base64.b64encode(data.encode('utf-8'))
    return encode64.decode('utf-8')


def decode64_str(data):
    decode64 = base64.b64decode(data)
    decode64_str = decode64.decode('utf-8')
    return decode64_str


# class MemoTask(FastHttpUser):
#     host = "https://www.retone-hearing.fit"
#     # wait_time = constant(1)
#     # header = {"Content-Type": "application/json"}
#     cookie = get_cookie()
#     # default_headers = {"Content-Type": "application/json"}
#     def on_start(self):
#         numbers_of_user = True
#         if numbers_of_user == True:
#             self.header = {"Cookie": f"hearingaid_user={get_cookie()}",
#                            "Content-Type": "application/json"}
#         else:
#             self.header = {"Cookie": f"hearingaid_user={self.cookie}",
#                            "Content-Type": "application/json"}
#     @task
#     @tag('search')
def del_memo(username):


    header = {"Cookie": f"hearingaid_user={cookie}","Content-Type": "application/json"}
    get_id_url = '/platformRetoneFit/api/memo/needAppUserAuth/responseEncode/requestDecode/getAllMemo'
    with requests.request('post', get_id_url, headers=header) as resp:
        try:
            if resp.status_code > 400 or (resp.js['data'] is None and resp.json()['description'] is not None):
                loguru.Logger.info(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
            else:
                if resp.json()['data']:
                    data = json.loads(decode64_str(resp.json()['data']))
                    delete_memo = '/platformRetoneFit/api/memo/needAppUserAuth/responseEncode/requestDecode/batchDeleteMemo'
                    data = {
                        "memoIdList": data
                    }
                    with requests.request('post', delete_memo, data=enconde_bs64(data), headers=header) as resp:
                            if resp.status_code > 400 or (
                                    resp.js['data'] is None and resp.js['description'] is not None):
                                loguru.Logger.info(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
                            else:
                                loguru.Logger.info('success')
                resp.success()
        except TypeError:
            loguru.Logger.info(TypeError)
        except JSONDecodeError:
            loguru.Logger.info("Response could not be decoded as JSON")
        except KeyError:
            loguru.Logger.info("Response did not contain expected key 'data'")
    # @task
    # def del_func(self):
    #     delete_memo = '/platformRetoneFit/api/memo/needAppUserAuth/responseEncode/requestDecode/batchDeleteMemo'
    #     data = {
    #         "memoIdList": ["454879746514"]
    #     }
    #     with self.rest('post', delete_memo, data=enconde_bs64(data), headers=self.header) as resp:
    #         if resp.status_code > 400 or (resp.js['data'] is None and resp.js['description'] is not None):
    #             resp.failure(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
    #         else:
    #             resp.success()


if __name__ == '__main__':
    # run_single_user(MemoTask)

    test1 = get_cookie()
    print(test1)